package org.dydl.common.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

/**
 * Created by xin on 15/1/7.
 */

public class CAPTCHAAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	private String servletPath;

	public CAPTCHAAuthenticationFilter(String servletPath) {
		super(servletPath);
		this.servletPath = servletPath;
		// setAuthenticationFailureHandler(new
		// SimpleUrlAuthenticationFailureHandler(failureUrl));

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		String path = req.getServletPath() != null ? req.getServletPath() : req.getPathInfo();
		if ("POST".equalsIgnoreCase(req.getMethod()) && servletPath.equals(path)) {
			if (!checkValidateCode(req)) {
				res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "验证码错误！");
				return;
			}
		}
		chain.doFilter(request, response);
	}

	protected boolean checkValidateCode(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String result_verifyCode = session.getAttribute("verifyResult").toString(); // 获取存于session的验证值
		String user_verifyCode = request.getParameter("verifyCode");// 获取用户输入验证码
		if (null == user_verifyCode || !result_verifyCode.equalsIgnoreCase(user_verifyCode)) {
			return false;
		}
		session.removeAttribute("verifyResult");
		return true;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException {
		return null;

	}

}
